package com.ly.hotel.spainterface.jxd.dialog;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.ly.hotel.R;
import com.ly.hotel.common.MyApplication;
import com.ly.hotel.common.MyLogsManager;
import com.ly.hotel.msgevent.SendLogEvent;
import com.ly.hotel.spainterface.NmSwipeCardUtils;
import com.ly.hotel.spainterface.OnSwipeCardInterface;
import com.ly.hotel.spainterface.jxd.activity.JxdJSPopupWindow;
import com.ly.hotel.spainterface.jxd.bean.JxdGuestCardBean;
import com.ly.hotel.spainterface.jxd.bean.MachineBean;
import com.ly.hotel.spainterface.jxd.bean.MySpaceBean;
import com.ly.hotel.spainterface.jxd.bean.PluginBean;
import com.ly.hotel.spainterface.jxd.event.JxdCloseJSDetailDialogEvent;
import com.ly.hotel.spainterface.jxd.utils.GsonUtils;
import com.ly.hotel.spainterface.jxd.utils.OkHttpUtils;
import com.ly.hotel.spainterface.jxd.utils.TimeUtils;
import com.ly.hotel.spainterface.jxd.utils.UdpUtils;
import com.ly.hotel.spainterface.jxd.utils.XmlParseUtils;
import com.ly.hotel.util.IdChangeUtil;
import com.ly.hotel.util.ProcessWaitingUtil;

import de.greenrobot.event.EventBus;

/**
 * Created by ThinkPad on 2018/3/29.
 */

public class JxdPopArrangeDialog extends Dialog {

    private Context mContext;
    private Animation alphaAnimation;
    private TextView jsFirstStep;
    private ImageView jsFirstArrow;
    private TextView jsSecondStep;
    private TextView dialogCloseTimer;
    private NmSwipeCardUtils swipeCardUtils;
    private final String TAG = "JxdJSActivity";
    private PluginBean pluginBean;
    private final int GUEST_CARD_TRANSLATED = 3;// 客人手牌转换
    private final int OPERATOR_CARD_TRANSLATED = 4;// 操作员手牌转换
    private final int ARRANGE_THERAPY = 5;
    private int step = 1;// 步数
    private TextView resultTextTips;
    private ImageView resultImageTips;
    private String massageName;// 选择的做钟名称
    private MachineBean machineBean;// 电视信息（座位号、接口ip和端口等）
    private String isSpec;// 起钟类型（点击图片、搜索进入都为点钟，推荐进入为轮牌）
    private String artNo;// 技师号
    private String keyNo;// 客人手牌号
    private int countTime = 9;// 窗口关闭倒计时(单位为秒)
    private final int PUT_MY_SPACE_DATA = 6;// 将安排时间和次数保存到服务器中
    private final int GET_MY_SPACE_DATA = 7;// 从服务器中获取手牌的上次的安排时间和次数；
    private String closeTips;
    private String timeUnit;
    private ImageButton arrangeClose;
    private TextView arrangeItemName;
    private TextView arrangeTherapyNo;
    long nowTime = 0;// 当前时间
    private int arrangeNum;// 安排的技师数目
    private boolean isOverTime = false;// 是否超过配置表中的时间

    public JxdPopArrangeDialog(JxdJSPopupWindow context, int theme) {
        super(context, theme);
        mContext = MyApplication.getContext();
        alphaAnimation = AnimationUtils.loadAnimation(context, R.anim.alpha_anim);
    }

    @Override
    protected void onStart() {
        super.onStart();
        closeTips = mContext.getResources().getString(R.string.xf_window_close);
        timeUnit = mContext.getResources().getString(R.string.xf_time_unit);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jxd_arrange_layout);
        swipeCardUtils = new NmSwipeCardUtils(new OnSwipeCardInterface() {
            @Override
            public void swipeCardListener(String cardId) {
                String newId = cardId.replaceAll("\r\n", "");
                if(newId.length() == 10){
                    try {
                        long b = Long.parseLong(newId);
                        if(!TextUtils.isEmpty(pluginBean.getCardtype())){
                            newId = IdChangeUtil.getId(newId,pluginBean.getCardtype());
                        }
                        if(step == 1){
                            guestCardTranslated(newId,pluginBean.getIp(),pluginBean.getPort());
                        }
                        if(step == 2){
                            operatorTranslated(newId,pluginBean.getIp(),pluginBean.getPort());
                        }

                    }catch (NumberFormatException e){
                        Log.e(TAG,"刷卡出现乱码，重刷！");
                        swipeCardUtils.initSwipe();
                    }
                }else {
                    Log.e(TAG,"刷卡不足10位，重刷！");
                    swipeCardUtils.initSwipe();
                }
            }
        });
        initView();
    }

    public void initView(){
        arrangeClose = findViewById(R.id.arrange_dialog_close);
        arrangeItemName = findViewById(R.id.arrange_item_name);
        arrangeTherapyNo = findViewById(R.id.arrange_therapy_no);
        resultTextTips = findViewById(R.id.result_text_tips);
        resultImageTips = findViewById(R.id.result_image_tips);
        jsFirstStep = findViewById(R.id.js_first_step);
        jsFirstArrow = findViewById(R.id.js_first_arrow);
        jsSecondStep = findViewById(R.id.js_second_step);
        dialogCloseTimer = findViewById(R.id.dialog_close_timer);

        arrangeItemName.setText(Html.fromHtml(mContext.getResources().getString(R.string.item_is)+ "<font color='#00DFFF'>" + massageName + "</font>"));
        arrangeTherapyNo.setText(Html.fromHtml(mContext.getResources().getString(R.string.technician_is) + "<font color='#00DFFF'>" + artNo + "</font>"));

        initFirstStep();
        initStep();
        closeDialog();
    }

    public void closeDialog(){
        arrangeClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                swipeCardUtils.setOnSwipeFlag(false);
                dismiss();
            }
        });
    }

    // 根据配置，设置不同的步骤
    public void initStep(){
        if(pluginBean != null ){
            jsFirstStep.setVisibility(View.VISIBLE);
            jsFirstArrow.setVisibility(View.VISIBLE);
            jsSecondStep.setVisibility(View.VISIBLE);
            //1.请刷您的手牌
            jsFirstStep.setText(mContext.getResources().getString(R.string.xf_swipe));
        }
    }

    // 设置步骤动画
    public void initFirstStep(){
        jsFirstStep.setAnimation(alphaAnimation);
        jsFirstArrow.setAlpha(1.0f);
        jsSecondStep.setAlpha(0.2f);

        swipeCardUtils.initSwipe();
    }

    public void showArrangeDialogClose(){
        dialogCloseTimer.setVisibility(View.VISIBLE);
        final Handler handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if(msg.what > 0){
                    dialogCloseTimer.setText(closeTips + msg.what + timeUnit);
                }else{
                    dismiss();
                }
            }
        };

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if(countTime > 0){
                    countTime --;
                }
                handler.sendEmptyMessage(countTime);
                handler.postDelayed(this,1000);// 每隔一秒发送消息
            }
        };
        handler.postDelayed(runnable,0);//
    }

    // 向服务器中提交安排时间和次数
    public void setArrangeTimeAndCount(){
        try {
            nowTime = TimeUtils.getSystemMills();
        }catch (Exception e){}

        String req = "http://" + machineBean.getServerIP() + ":" + machineBean.getServerPORT() + "/api/put-my-space.json?key="
                + keyNo + "&value=" + nowTime + "," + arrangeNum;
        OkHttpUtils.getInstance().getTextResource(req,handler,PUT_MY_SPACE_DATA);
    }

    // 向服务器中提交安排时间和次数
    public void getArrangeTimeAndCount(){
        String req = "http://" + machineBean.getServerIP() + ":" + machineBean.getServerPORT() + "/api/get-my-space.json?key="
                + keyNo;
        OkHttpUtils.getInstance().getTextResource(req,handler,GET_MY_SPACE_DATA);
    }

    // 客人桑拿卡号转匙牌号
    public void guestCardTranslated(String cardId,String cashierIP,String cashierPORT){
        ProcessWaitingUtil.showProcessDialog(mContext,mContext.getResources().getString(R.string.loading_tips),20000);
        String req = "<gs ver=\"1.0\" function=\"桑拿卡号转匙牌号\" mode = \"request\"><ArtFlag>0</ArtFlag><RfCardno>" + cardId + "</RfCardno></gs>";
        UdpUtils udpUtils = new UdpUtils();
        udpUtils.getUdpResult(cashierIP,cashierPORT,req,handler,GUEST_CARD_TRANSLATED);
    }

    // 操作员卡号转匙牌号
    public void operatorTranslated(String cardId,String cashierIP,String cashierPORT){
        ProcessWaitingUtil.showProcessDialog(mContext,mContext.getResources().getString(R.string.loading_tips),20000);
        String req = "<gs ver=\"1.0\" function=\"桑拿操作员确认\" mode = \"request\">" +
                "<CardId>" + cardId + "</CardId></gs>";
        UdpUtils udpUtils = new UdpUtils();
        udpUtils.getUdpResult(cashierIP,cashierPORT,req,handler,OPERATOR_CARD_TRANSLATED);
    }

    // 调用选技师接口(isSpec为起钟类型)
    public void arrangeTherapy(){
        String req = "<gs ver=\"1.0\" function=\"选技师\" mode = \"request\"><KeyNo>" + keyNo + "</KeyNo><ArtNo>"
                + artNo + "</ArtNo><RoomNo>" + machineBean.getTvName() + "</RoomNo><MType>" + massageName + "</MType>" +
                "<IsSpec>" + isSpec + "</IsSpec></gs>";
        UdpUtils udpUtils = new UdpUtils();
        udpUtils.getUdpResult(pluginBean.getIp(),pluginBean.getPort(),req,handler,ARRANGE_THERAPY);
    }


    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    Log.i(TAG,"接口返回：" + msg.obj.toString());
                    String resultString = msg.obj.toString();
                    if(msg.arg1 == GUEST_CARD_TRANSLATED){
                        if(resultString.startsWith("Msg") || TextUtils.isEmpty(resultString)){
                            Log.i(TAG,"客人桑拿卡号转匙牌号出错");
                            resultTextTips.setText(resultString);
                            resultImageTips.setVisibility(View.VISIBLE);
                            resultImageTips.setImageResource(R.drawable.xf_buy_err);
                            jsFirstStep.clearAnimation();
                            jsFirstStep.setAlpha(0.2f);
                            jsFirstArrow.setAlpha(0.2f);
                            jsSecondStep.setAlpha(1.0f);
                            jsSecondStep.setText(mContext.getResources().getString(R.string.arrange_fails));
                            ProcessWaitingUtil.closeProcessDialog();
                        }else{
                            JxdGuestCardBean cardBean = XmlParseUtils.getInstance().parseGuestCard(resultString);
                            keyNo = cardBean.getKeyno();
                            Log.i(TAG,"keyNo=" + keyNo);
                            // 获取服务器中该手牌安排的次数和上次安排的时间
                            getArrangeTimeAndCount();
                        }
                    }else if(msg.arg1 == GET_MY_SPACE_DATA){
                        MySpaceBean mySpaceBean = GsonUtils.parseSimpleJson(resultString,MySpaceBean.class);
                        if(mySpaceBean.getCode() == 200){
                            try {
                                String[] timeAndCount = mySpaceBean.getData().split(",");
                                long nowTime = TimeUtils.getSystemMills();
                                long arrangeTime = Long.parseLong(timeAndCount[0]);
                                arrangeNum = Integer.parseInt(timeAndCount[1]);
                                // 两次安排的时间间隔
                                int intervalTime = (int) ((nowTime - arrangeTime) / (1000 * 60));
                                //Log.i(TAG,"安排时间间隔=" + intervalTime + "分钟 安排的次数=" + arrangeNum);
                                int arrangeTimeOut = Integer.parseInt(pluginBean.getArrangeTimeOut());
                                if(intervalTime >= arrangeTimeOut){// 超过配置的时间间隔
                                    isOverTime = true;
                                    arrangeTherapy();
                                }else{// 还没超过配置的时间间隔
                                    if(arrangeNum < pluginBean.getArrange() || pluginBean.getArrange()== 0){
                                        arrangeTherapy();
                                    }else{
                                        jsFirstStep.clearAnimation();
                                        jsFirstStep.setAlpha(0.2f);
                                        jsFirstArrow.setAlpha(0.2f);
                                        jsSecondStep.setAlpha(1.0f);
                                        jsSecondStep.setText(mContext.getResources().getString(R.string.arrange_fails));
                                        resultImageTips.setVisibility(View.VISIBLE);
                                        resultImageTips.setImageResource(R.drawable.xf_buy_err);
                                        resultTextTips.setText("该手牌已超过安排项目次数的上限！");
                                        ProcessWaitingUtil.closeProcessDialog();
                                    }
                                }
                            }catch (Exception e){
                                // 异常之后，仍然可以安排（调选技师接口）
                                arrangeTherapy();
                            }
                        }else{
                            // 没有获取到安排次数和时间，就直接调用选技师接口
                            arrangeTherapy();
                        }
                    }else if(msg.arg1 == ARRANGE_THERAPY){// 选技师接口返回
                        if(resultString.startsWith("Msg") || TextUtils.isEmpty(resultString)){// 接口返回失败
                            jsFirstStep.clearAnimation();
                            jsFirstStep.setAlpha(0.2f);
                            jsFirstArrow.setAlpha(0.2f);
                            jsSecondStep.setAlpha(1.0f);
                            jsSecondStep.setText(mContext.getResources().getString(R.string.arrange_fails));
                            resultImageTips.setVisibility(View.VISIBLE);
                            resultImageTips.setImageResource(R.drawable.xf_buy_err);
                            resultTextTips.setText(resultString);
                            ProcessWaitingUtil.closeProcessDialog();
                        }else{
                            jsFirstStep.clearAnimation();
                            jsFirstStep.setAlpha(0.2f);
                            jsFirstArrow.setAlpha(0.2f);
                            jsSecondStep.setAlpha(1.0f);
                            jsSecondStep.setText(mContext.getResources().getString(R.string.arrange_success));
                            resultImageTips.setVisibility(View.VISIBLE);
                            resultImageTips.setImageResource(R.drawable.xf_buy_suc);
                            resultTextTips.setText(mContext.getResources().getString(R.string.arrange_success_tips));
                            ProcessWaitingUtil.closeProcessDialog();
                            if(isOverTime){
                                arrangeNum = 1;// 安排时间重新置为1
                            }else{
                                arrangeNum ++;// 增加安排的次数
                            }
                            setArrangeTimeAndCount();//将安排时间和次数保存到服务器
                            showArrangeDialogClose();
                            // 安排成功后，通知DetailDialog关闭
                            EventBus.getDefault().post(new JxdCloseJSDetailDialogEvent());
                            // 上传云端日志
                            EventBus.getDefault().post(new SendLogEvent(MyLogsManager.CLOUD_LOGS_JISHI + "\t" +
                                    MyApplication.interfaceVersion + "\t" + "安排成功" + "\t" + machineBean.getTvName() + "\t" + massageName + "\t" + artNo));
                        }
                        ProcessWaitingUtil.closeProcessDialog();
                    }else if(msg.arg1 == PUT_MY_SPACE_DATA){
                        Log.i(TAG,"手牌安排时间和次数保存到服务器成功！");
                    }
                    break;

                case 2:
                    if(msg.arg2 == GET_MY_SPACE_DATA){
                        ProcessWaitingUtil.closeProcessDialog();
                        jsFirstStep.clearAnimation();
                        jsFirstStep.setAlpha(0.2f);
                        jsFirstArrow.setAlpha(0.2f);
                        jsSecondStep.setAlpha(1.0f);
                        jsSecondStep.setText(mContext.getResources().getString(R.string.arrange_fails));
                        resultImageTips.setVisibility(View.VISIBLE);
                        resultImageTips.setImageResource(R.drawable.xf_buy_err);
                        resultTextTips.setText(mContext.getResources().getString(R.string.connect_err));
                    }else if(msg.arg2 == PUT_MY_SPACE_DATA){
                        Log.i(TAG,"手牌安排时间和次数保存到服务器失败！");
                    }
                    break;

                default:
                    break;
            }
        }
    };

    public void setPluginBean(PluginBean pluginBean) {
        this.pluginBean = pluginBean;
    }

    public void setMassageName(String massageName) {
        this.massageName = massageName;
    }

    public void setMachineBean(MachineBean machineBean) {
        this.machineBean = machineBean;
    }

    public void setIsSpec(String isSpec) {
        this.isSpec = isSpec;
    }

    public void setArtNo(String artNo) {
        this.artNo = artNo;
    }
}
